<?php

namespace app\admin\controller;

use app\model\BizPayRecordModel;
use app\model\UserModel;
use app\model\BizModel;
use support\Request;
use support\Response;
use Exception;

class BizPayRecordController
{
    /**
     * 获取商家支付记录列表
     * @param Request $request
     * @return Response
     */
    public function index(Request $request): Response
    {
        try {
            $current = (int)$request->get('current', 1);
            $pageSize = (int)$request->get('pageSize', 10);
            $bizId = $request->get('biz_id', ''); // 商家ID搜索
            $userPhone = $request->get('user_phone', ''); // 用户手机号搜索
            $payStatus = $request->get('pay_status', ''); // 支付状态筛选
            $startTime = $request->get('start_time', ''); // 开始时间
            $endTime = $request->get('end_time', ''); // 结束时间
            
            $query = BizPayRecordModel::query()
                ->select('biz_pay_record.*')
                ->orderBy('created_at', 'desc');
            
            // 商家ID搜索
            if (!empty($bizId)) {
                $query->where('biz_id', 'like', '%' . $bizId . '%');
            }
            
            // 用户手机号搜索
            if (!empty($userPhone)) {
                $query->join('user', 'biz_pay_record.user_id', '=', 'user.id')
                      ->where('user.phone', 'like', '%' . $userPhone . '%');
            }
            
            // 支付状态筛选
            if ($payStatus !== '') {
                $query->where('pay_status', $payStatus);
            }
            
            // 时间范围筛选
            if (!empty($startTime)) {
                $startTimestamp = strtotime($startTime);
                $query->where('created_at', '>=', $startTimestamp);
            }
            
            if (!empty($endTime)) {
                $endTimestamp = strtotime($endTime . ' 23:59:59');
                $query->where('created_at', '<=', $endTimestamp);
            }
                
            $total = $query->count();
            $list = $query->offset(($current - 1) * $pageSize)
                ->limit($pageSize)
                ->get();

            // 处理数据，添加关联信息
            foreach ($list as &$item) {
                // 格式化时间
                $item['created_at'] = date('Y-m-d H:i:s', $item->created_at);
                $item['updated_at'] = date('Y-m-d H:i:s', $item->updated_at);
                if ($item->paid_at > 0) {
                    $item['paid_at'] = date('Y-m-d H:i:s', $item->paid_at);
                }else{
                    $item['paid_at'] = false;
                }
                
                // 获取用户手机号
                $user = UserModel::find($item->user_id);
                $item['user_phone'] = $user ? $user->phone : '';
                
                // 获取商家名称
                $biz = BizModel::where('id', $item->biz_id)->first();
                $item['biz_name'] = $biz ? $biz->name : '';
                
                // 格式化金额
                $item['pay_price'] = number_format($item->pay_price, 2);
                $item['pay_money'] = number_format($item->pay_money, 2);
                $item['money'] = number_format($item->money, 2);
                
                // 格式化折扣
                $item['discount'] = $item->discount ? number_format($item->discount, 1) . '%' : '-';
                
                // 支付状态文本
                $item['pay_status_text'] = $item->pay_status == 1 ? '已支付' : '未支付';
                $item['score_status_text'] = $item->score_status == 1 ? '已支付' : '未支付';
                $item['money_status_text'] = $item->money_status == 1 ? '已支付' : '未支付';
            }
                
            return json([
                'data' => [
                    'list' => $list,
                    'total' => $total
                ],
                'msg' => '获取成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取商家支付记录详情
     * @param Request $request
     * @return Response
     */
    public function detail(Request $request): Response
    {
        try {
            $id = $request->get('id');
            
            if (empty($id)) {
                throw new Exception('参数错误');
            }

            $record = BizPayRecordModel::find($id);
            if (!$record) {
                throw new Exception('记录不存在');
            }

            // 格式化时间
            $record['created_at'] = date('Y-m-d H:i:s', $record->created_at);
            $record['updated_at'] = date('Y-m-d H:i:s', $record->updated_at);
            if ($record->paid_at) {
                $record['paid_at'] = date('Y-m-d H:i:s', $record->paid_at);
            }
            
            // 获取用户信息
            $user = UserModel::find($record->user_id);
            $record['user_phone'] = $user ? $user->phone : '';
            $record['user_name'] = $user ? $user->name : '';
            
            // 获取商家信息
            $biz = BizModel::where('id', $record->biz_id)->first();
            $record['biz_name'] = $biz ? $biz->name : '';
            $record['biz_phone'] = $biz ? $biz->biz_phone : '';
            
            // 格式化金额
            $record['pay_price'] = number_format($record->pay_price, 2);
            $record['pay_money'] = number_format($record->pay_money, 2);
            $record['money'] = number_format($record->money, 2);
            
            // 格式化折扣
            $record['discount'] = $record->discount ? number_format($record->discount, 1) . '%' : '-';
            
            // 支付状态文本
            $record['pay_status_text'] = $record->pay_status == 1 ? '已支付' : '未支付';
            $record['score_status_text'] = $record->score_status == 1 ? '已支付' : '未支付';
            $record['money_status_text'] = $record->money_status == 1 ? '已支付' : '未支付';

            return json([
                'data' => $record,
                'msg' => '获取成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 删除商家支付记录
     * @param Request $request
     * @return Response
     */
    public function delete(Request $request): Response
    {
        try {
            $id = $request->post('id');
            
            if (empty($id)) {
                throw new Exception('参数错误');
            }

            $record = BizPayRecordModel::find($id);
            if (!$record) {
                throw new Exception('记录不存在');
            }

            if (!$record->delete()) {
                throw new Exception('删除失败');
            }

            return json([
                'data' => null,
                'msg' => '删除成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }
} 